package simmar.utilities;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

public class IO
{
    /**
     * 
     * @param map
     */
    public static <T> void SaveObject(T obj, String objName)
    {
        try
        {
            Logger.logLine("Creating File/Object output stream...");

            FileOutputStream fileOut = new FileOutputStream("./src/simmar/resources/" + objName + ".ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            Logger.logLine("Writing '" + objName + "' to file...");
            out.writeObject(obj);

            Logger.logLine("Closing all output streams...\n");
            out.close();
            fileOut.close();

        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T LoadObject(String objName)
    {
        T obj = null;

        try
        {
            Logger.logLine("Creating File/Object input stream...");

            FileInputStream fileIn = new FileInputStream("./src/simmar/resources/" + objName + ".ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);

            Logger.logLine("Loading '" + objName + "'...");
            obj = (T) in.readObject();

            Logger.logLine("Closing all input streams...\n");
            in.close();
            fileIn.close();

        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return obj;
    }
}